package com.alcohol.auth.server.support.grant.password;

import com.alcohol.auth.server.service.SysOAuthClientService;
import com.alcohol.auth.server.support.grant.base.BaseAuthenticationProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;

/**
 * 密码认证处理器
 * @author LiXinYu
 * @date 2025/11/8
 */
@Slf4j
public class PasswordAuthenticationProvider extends BaseAuthenticationProvider<PasswordAuthenticationToken> {

    /**
     * OAuth2-密码认证提供者
     * @param authorizationService 授权服务
     * @param tokenGenerator  token生成器
     * @param sysOAuthClientService 客户端信息服务
     */
    public PasswordAuthenticationProvider(OAuth2AuthorizationService authorizationService,
                                          OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator,
                                          SysOAuthClientService sysOAuthClientService,
                                          AuthenticationManager authenticationManager) {
        super(authorizationService, tokenGenerator, sysOAuthClientService, authenticationManager);
    }

    /**
     * 构建用户名密码认证令牌
     * @param authenticationToken 认证信息
     * @return 用户名密码认证令牌
     */
    @Override
    public UsernamePasswordAuthenticationToken buildUserToken(PasswordAuthenticationToken authenticationToken) {
        String username = authenticationToken.getUsername();
        String password = authenticationToken.getPassword();
        return new UsernamePasswordAuthenticationToken(username, password);
    }

    /**
     * 认证对象类型是否支持
     * @param authentication 认证对象类型
     * @return 是否支持
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(PasswordAuthenticationToken.class);
    }
}
